require"luarocks.require"
require"lfs"
require"markdown"
require"cosmo"
require "logging.file"
taglet = require"luadoc.taglet.standard"


---------------------------------------------------------------------------------------------------
-- The main template
---------------------------------------------------------------------------------------------------
TEMPLATE = [[<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="description" content="$package: $summary">
  <meta name="keywords" content="$keywords">
  <title>$package</title>
  <style type="text/css">
    body { color:#000; background:#fff; }
    #header { width:100%;
       text-align:center;  
       border-top:solid #aaa 1px;
       border-bottom:solid #aaa 1px;
    }
    #header p { margin-left:0; }
    p { margin-left:3px; }
    pre { background-color:#ffe; white-space:pre; padding-left:3ex; border-left: 1px solid gray; margin-left: 10px}

    table.index { border: 1px #00007f; }
    table.index td { text-align: left; vertical-align: top; }
    table.index ul { padding-top: 0em; margin-top: 0em; }

    table {
     border: 1px solid black;
	 border-collapse: collapse;
     margin-left: auto;
     margin-right: auto;
    }
    th {
     border: 1px solid black;
     padding: 0.5em;
    }
    td {
     border: 1px solid black;
     padding: 0.5em;
    }
    div.header, div.footer { margin-left: 0em; }
  </style>
</head>
<body>
 <div id="header">
  <img border=0 alt="$package logo" src="$logo"/>
  <p>$summary</p>
  <p>
   <a name="toc"></a>$do_toc[=[<a href="#$anchor">$item</a>]=],[=[ &middot; <a href="#$anchor">$item</a>]=]
  </p>
 </div>
 $body
</table>
</table>
</body>
</html>
]]

---------------------------------------------------------------------------------------------------
-- The template for the LuaDoc section
---------------------------------------------------------------------------------------------------
LUADOC = [[
 <table style="width:100%" class="function_list">
 $do_modules[=[
  <tr>
   <td colspan=2 style='background: #dddddd;'>
    <h2>$module</h2>
    <p>$description</p>
    $if_release[==[Release: $release]==]
   </td>
  </tr>
  $do_functions[==[
   <tr>
	<td class="name" width="300px" style="vertical-align: top;"><b>$fname()</b></td>
	<td class="summary" >$summary
     <dl>
      $do_params[===[<dt><color="green"><b>$param</b></font>: <dd>$description</dd></dt>]===]
     </dl>
     Returns: $do_returns[====[<font color="purple">$ret</color>]====],[====[<b>$i.</b> <font color="purple">$ret</color>]====]
    </td>
   </tr>
  ]==]
 ]=]
]]

---------------------------------------------------------------------------------------------------
-- Generates LuaDoc
---------------------------------------------------------------------------------------------------

function luadoc(modules)
   lfs.chdir("lua")
   taglet.logger = logging.file("luadoc.log")
   taglet.options = {}
   local doc = taglet.start(modules)
   lfs.chdir("..")

   return cosmo.f(LUADOC){
       do_modules = function() for i, name in ipairs(doc.modules) do
                       local m = doc.modules[name]
                       cosmo.yield {
                          module       = name,
                          description  = m.description,
                          if_release   = cosmo.c(m.release){release = m.release},
                          do_functions = function() for j, fname in ipairs(m.functions) do
                                            local f = m.functions[fname]
                                            cosmo.yield{
                                            fname = fname,
                                            summary = f.summary,
                                            do_params  = function() for p = 1, #(f.param or {})do
                                                            cosmo.yield{param=f.param[p], description = f.param[f.param[p]] }
                                                         end end,
                                            do_returns = function() if type(f.ret) == "string" then 
                                                            cosmo.yield{ret=f.ret, i=1}
                                                         elseif type(f.ret) == "table" then
                                                            for k,r in ipairs(f.ret) do
                                                               cosmo.yield{ i=k, ret=r, _template=2}
                                                            end
                                                         end end,
                                         }
                                         end end,
                       }
                       end end,
    }
end


---------------------------------------------------------------------------------------------------
-- Used to include the content of another file
---------------------------------------------------------------------------------------------------

function include(path)
   local f, x = io.open(path)
   return f:read("*all")
end


---------------------------------------------------------------------------------------------------
-- "Main"
---------------------------------------------------------------------------------------------------

function petrodoc(spec)

   spec.recent_releases = "<ul>"
   for i, version in ipairs(versions) do
      spec.version = version
      spec.recent_releases = spec.recent_releases..cosmo.fill("<li><a href='"..spec.download.."'>$package-$version</a></li>\n", spec)
   end
   spec.recent_releases = spec.recent_releases.."</ul>"

   spec.body = ""
   for i,item in ipairs(spec.toc) do
      spec.anchor = item[1]
      spec.h1 = item[1]
      spec.text = cosmo.fill(item[2], spec)
      spec.body=spec.body..cosmo.fill('\n\n<a name="$anchor"></a><h1>$h1</h1>\n$text\n', spec)
   end

   spec.do_toc = function()
                     for i, item in ipairs(spec.toc) do
                        --item.anchor = string.gsub(item[1], "([^%w]*)", "_")
                        local template = 1
                        if i > 1 then template = 2 end
                        cosmo.yield {
                           anchor = item[1],
                           item = item[1],
                           _template = template
                        }
                     end
                  end

   print(spec.package..".html")
   local html = io.open(spec.package..".html", "w")
   html:write(cosmo.fill(TEMPLATE, spec))
   html:close()
end



local dir = arg[1]
lfs.chdir(dir)
local petrofunc, err = loadfile("petrodoc")
if not petrofunc then error(err) end

local spec = getfenv(petrofunc())
petrodoc(spec)


